﻿using CompanyRatings.PerfTest.ConsoleApp.TestData;
using CompanyRatings.PerfTest.Models.Query;
using CompanyRatings.SQL.PerfTest.ConsoleApp.TestData;
using PerfTestLib.Result;
using PerfTestLib.Runtime;
using PerfTestLib.Spec;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CompanyRatings.SQL.PerfTest.ConsoleApp.Tests
{
    public abstract class CrTestBase
    {
        readonly TestRunner<CrQuery> _testRunner;
        public readonly TestDataType TestDataType;

        public CrTestBase(TestDataType dataType)
        {
            this.TestDataType = dataType;

            // get test data
            TestDataSource testDataSrc = new TestDataSource();
            TestSpec<CrQuery> spec = testDataSrc.GetTestData(dataType);

            // create test runner
            var specResRepo = new MongoTestSpecResultRepository(ConfigurationManager.ConnectionStrings["TestSpecResultDb"].ConnectionString);
            this._testRunner = new TestRunner<CrQuery>(spec, ProcessTestData, specResRepo);
        }

        public Task<TestSpecResult> Run()
        {
            // run test
            Task<TestSpecResult> runTask = this._testRunner.Run();

            // report progress to console
            this._testRunner.ReportProgressToConsole(runTask);

            // write result as CSV
            runTask.ContinueWith(t =>
                {
                    t.Result.SaveToCsv();
                });

            return runTask;
        }

        public void Stop()
        {
            this._testRunner.Stop();
        }

        public void Wait()
        {
            this._testRunner.Wait();
        }

        protected abstract object ProcessTestData(TestSpecIterationInstance<CrQuery> testIteration);
    }
}
